package org.rbac.serv;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Query;
import org.rbac.po.PermissionUserRoleRef;
import org.rbac.po.PermissionUsers;
import org.rbac.util.SqlCmdUtil;
import org.rbac.vo.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.kingschan.encrypt.CommomEncrypt;
import com.kingschan.lang.date.TimeStampUtil;

/**
 * 用户服务
 * 
 * <pre>
 * 项目名称：rbac
 * 类名称：UserServices
 * 类描述：用户服务
 * 创建人：唐家林(tjl)
 * 创建时间：2014-9-25 下午4:33:33
 * 修改人：
 * 修改时间：
 * 修改备注：
 * @version
 * </pre>
 */
@Service
public class UserServices extends CommonServices {
	
	/**
	 * 用户登录验证
	 * 
	 * @param account
	 *            账户
	 * @param password
	 *            密码
	 * @return 当且仅当验证成功返回true
	 */
	public User login(String account, String password){
		if (null == account || account.length() <= 0 || null == password || password.length() <= 0) {
			return null;
		}
		// 计算密码MD5码
		password = CommomEncrypt.MD5(password);
		String hql = "SELECT pu FROM PermissionUsers pu WHERE pu.UStatus = 1 AND pu.UAccount = ? AND pu.UPwd = ?";
		PermissionUsers result = (PermissionUsers) getDao().uniqueQueryByHql(hql, account, password);
		if (null == result) {
			return null;
		}
		User user = new User();
		BeanUtils.copyProperties(result, user, new String[]{"UPwd"});
		return user;
	}

	/**
	 * 用户权限
	 * 
	 * @param id
	 *            用户主键
	 * @return 返回用户所有有效权限信息
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> userAuthority(HttpServletRequest request, Integer id){
		SqlCmdUtil sc = new SqlCmdUtil();           
		String sql = sc.getSqlCmdById("user", "userAuthority_All").getSql();//sc.getSqlCmdById("userAuthority_All", request).getSql();
		return (List<Map<String, Object>>)getDao().executeSQLQuery(sql, id);
	}

	/**
	 * 修改状态
	 * 
	 * @param ids
	 *            修改状态的数据主键
	 * @param status
	 *            状态(0:删除, 1:正常, 2:禁用)
	 * @throws Exception
	 */
	public void moidifyUserStatus(Integer[] ids, short status) throws Exception {
		String hql = "UPDATE PermissionUsers pu SET pu.UStatus = :status WHERE pu.id IN (:ids)";
		Query q = getDao().getSession().createQuery(hql);
		q.setParameter("status", status);
		q.setParameterList("ids", ids);
		q.executeUpdate();
	}

	/**
	 * 编辑用户(新增或修改)
	 * 
	 * @param u
	 *            操作的数据
	 */
	public void editUser(User u) {
		if (null == u) {
			return;
		}
		PermissionUsers user = null;
		if (null == u.getId()) {
			user = new PermissionUsers();
		} else {
			user = (PermissionUsers) getDao().get(PermissionUsers.class,
					u.getId());
		}
		// 属性值拷贝(拷贝r对象的属性值到role对象中对应名称的属性,且不拷贝id和RCdate的值)
		BeanUtils.copyProperties(u, user, new String[] { "id", "UCdate", "UStatus","UPwd" });

		if (null == u.getId()) {
		    if(null==u.getUPwd()||u.getUPwd().isEmpty()){
                u.setUPwd("123456");
            }
        }
		// 使用MD5加密密码,长度:32位
		if (!"".equals(u.getUPwd())) {
		    user.setUPwd(CommomEncrypt.MD5(u.getUPwd()));
        }
		if (null == u.getId()) {		    
			user.setUCdate(TimeStampUtil.getCurrentDate());
			short status = 1;
			user.setUStatus(status);
			getDao().save(user);
			u.setId(user.getId());
			bindRoles(u,true);
		} else {
			getDao().update(user);
			bindRoles(u,false);
		}
	}
	
	/**
	 * 绑定角色
	 * @param u
	 * @param isAdd
	 */
	public void bindRoles(User u,boolean isAdd){
	    if (null==u.getURoles()||u.getURoles().isEmpty()) {
            return;
        }
	    if (!isAdd) {
	        String delete_role_hql="delete PermissionUserRoleRef prf where prf.rfUserId=?"; 
            getDao().executeHQL(delete_role_hql, u.getId());                                
        }
	    PermissionUserRoleRef pur=null;
	    String [] roles_id=u.getURoles().split(",");
	    List<PermissionUserRoleRef> lis = new ArrayList<PermissionUserRoleRef>();
	    for (String rid : roles_id) {
            pur=new PermissionUserRoleRef(u.getId(), Integer.valueOf(rid));
            lis.add(pur);
        }
	    getDao().saveList(lis);
	    //URoles
	}
	
	/**
     * @查询用户所有资源
     * @return
     * @throws Exception
     */
	public List<Map> queryUserRes(Integer userId)throws Exception{
		List<Map> list = new ArrayList<Map>();
		try {
			String sql = new SqlCmdUtil().getSqlCmdById("user", "userAuthority_All").getSql();
			list = (List<Map>) getDao().executeSQLQuery(sql, userId);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return list;
		
	}
}
